package com.jiukuaidao.zhulin.module.order;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jiukuaidao.library.base.BaseActivity;
import com.jiukuaidao.library.common.dialog.CommDialog;
import com.jiukuaidao.library.common.dialog.CustomDialog;
import com.jiukuaidao.library.common.dialog.ICallBack;
import com.jiukuaidao.library.util.ToastUtil;
import com.jiukuaidao.zhulin.R;
import com.jiukuaidao.zhulin.data.TaskProvider;
import com.jiukuaidao.zhulin.entity.ApiOrderDetailInfo;
import com.jiukuaidao.zhulin.entity.EventRefreshComments;
import com.jiukuaidao.zhulin.module.CommContract;
import com.jiukuaidao.zhulin.module.CommPresenter;
import com.jiukuaidao.zhulin.module.order.contract.OrderDetailContract;
import com.jiukuaidao.zhulin.module.order.presenter.OrderDetailPresenter;
import com.jiukuaidao.zhulin.module.pay.wechat.WXPayContract;
import com.jiukuaidao.zhulin.module.pay.wechat.WXPayPresenter;
import com.jiukuaidao.zhulin.util.IntentUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author : BinarySatan
 * Date : 2016/6/3
 * Description :
 */
public class OrderDetailActivity extends BaseActivity<OrderDetailContract.Presenter> implements OrderDetailContract.View, CommContract.orderView, WXPayContract.View {

    @BindView(R.id.titile_left_imageview)
    ImageView mTitileLeftImageview; //标题栏左侧返回
    @BindView(R.id.titile_text)
    TextView mTitileText; //标题栏title
    @BindView(R.id.titile_right_text)
    TextView mTitileRightText; //标题栏右侧文字
    @BindView(R.id.tv_order_time)
    TextView mTvOrderTime;  // 刚下单时的订单时间.
    @BindView(R.id.tv_order_state)
    TextView mTvOrderState;
    @BindView(R.id.tv_tip_info)
    TextView mTvTipInfo; //提示信息 如: 订单商户确认中,请耐心等候
    @BindView(R.id.btn_pay)
    Button mBtnPay;   //支付按钮
    @BindView(R.id.ll_order_submit)
    LinearLayout mLLOrderSubmit;// 订单刚提交的布局
    @BindView(R.id.rl_receive_order)
    RelativeLayout mRLReceiveOrder;
    @BindView(R.id.btn_state)
    Button mBtnState;  //商家提交订单后的 按钮
    @BindView(R.id.order_number)
    TextView orderNumber;
    @BindView(R.id.tv_order_number)
    TextView mTvOrderNumber;  //订单编号
    @BindView(R.id.tv_shop_name)
    TextView mTvShopName; //店铺名
    @BindView(R.id.tv_contact_business)
    TextView mTvContactBusiness;  //联系商家
    @BindView(R.id.tv_receipt_address)
    TextView mTvReceiptAddress;
    @BindView(R.id.tv_receipt_number)
    TextView mTvReceiptNumber;
    @BindView(R.id.tv_receipt_name)
    TextView mTvReceiptName;
    @BindView(R.id.tv_pay_method)
    TextView mTvPayMethod;
    @BindView(R.id.tv_remark_info)
    TextView mTvRemarkInfo;
    @BindView(R.id.tv_invoice)
    TextView mTvInvoice;
    @BindView(R.id.ll_goods_detail)
    LinearLayout mLLGoodsDetail;
    @BindView(R.id.tv_shipment)
    TextView tvShipment;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;


    @BindView(R.id.ll_dynamic_circle_point)
    LinearLayout mLLDynamicCirclePoint; //动态添加原点
    @BindView(R.id.ll_dynamic_order_status)
    LinearLayout mLLDynamicOrderStauts; //动态添加订单状态

    private String mOrderNumber; //订单id

    private String mOrderCancelReason;//订单取消原因
    private ApiOrderDetailInfo mOrderDetailInfo;
    private CommPresenter mCommPresenter;
    private WXPayPresenter mWXPayPresenter;
    public static OrderDetailActivity mInstance;

    @Override
    protected View getTargetView() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void handleBundle(Bundle bundle) {
        mOrderNumber = bundle.getString("orderNumber");
    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        mInstance = this;
        mTitileLeftImageview.setImageResource(R.mipmap.ic_left_back);
        mTitileText.setText(getString(R.string.order_detail));
        mTitileRightText.setText(getString(R.string.order_cancel));

        new OrderDetailPresenter(TaskProvider.provideTasksRepository(this), this);
        mCommPresenter = new CommPresenter(TaskProvider.provideTasksRepository(this), this);
        mPresenter.start();
    }

    /**
     * 点击联系商家
     */
    @OnClick(R.id.tv_contact_business)
    public void clickContactBusiness() {
        IntentUtils.callPhone(this, mOrderDetailInfo.shopMobile);
    }


    @Subscribe
    public void onEventRefresh(EventRefreshComments refreshComments){

        refreshInfo();

    }

    /**
     * 商家确认订单 后的按钮
     */
    @OnClick(R.id.btn_state)
    public void clickBtnState() {
        if (mBtnState.getText().toString().contains(getString(R.string.receipt))) {//签收状态
            showDialogTwoBtn(getString(R.string.confirm_receipt), getString(R.string.cancel), getString(R.string.receipt), new ICallBack.TwoCallBack() {
                @Override
                public void left(CommDialog dialog) {

                }

                @Override
                public void right(CommDialog dialog) {
                    //调用订单签收接口
                    mCommPresenter.orderSign();
                }
            });


        }
    }

    @OnClick(R.id.titile_left_imageview)
    public void clickLeftBack() {
        this.finish();
    }

    @OnClick(R.id.btn_pay)
    public void clickBtnPay() {
        if (mOrderDetailInfo.payWay == 3) {
            mWXPayPresenter = new WXPayPresenter(TaskProvider.provideTasksRepository(this), this);
            mWXPayPresenter.loadData();
        }
    }


    /**
     * 点击title上的右侧文字
     */
    @OnClick(R.id.titile_right_text)
    public void clickTitleRightText() {

        String titleRightText = mTitileRightText.getText().toString();
        if (titleRightText.contains(getString(R.string.complaints))) {//如果是投诉
            Bundle b = new Bundle();
            b.putString("orderNumber", mOrderNumber);
            intentJump(ComplaintActivity.class, b);
            return;
        }

        if (titleRightText.contains(getString(R.string.order_cancel)))  //取消订单
            showOrderCancelDialog(); //显示取消订单原因对话框


    }

    String mRsnReason; //补充原因

    /**
     * 显示取消订单对话框
     */
    private void showOrderCancelDialog() {
        final CustomDialog dialog = new CustomDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_order_cancel, new FrameLayout(this), false);
        final RadioGroup rg = (RadioGroup) view.findViewById(R.id.rg_order_cancel);
        final RadioButton rb1 = (RadioButton) view.findViewById(R.id.rb_1);
        final RadioButton rb2 = (RadioButton) view.findViewById(R.id.rb_2);
        final RadioButton rb3 = (RadioButton) view.findViewById(R.id.rb_3);
        final RadioButton rb4 = (RadioButton) view.findViewById(R.id.rb_4);
        final RadioButton rb5 = (RadioButton) view.findViewById(R.id.rb_5);
        final EditText addReason = (EditText) view.findViewById(R.id.et_add_reason); //补充原因
        TextView wait = (TextView) view.findViewById(R.id.tv_wait); //再等等
        TextView orderCancel = (TextView) view.findViewById(R.id.tv_order_cancel); //取消订单


        wait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        orderCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rg.getCheckedRadioButtonId() != -1) {
                    mPresenter.orderCancel();
                    dialog.dismiss();
                    return;
                }

                ToastUtil.show("必须选择一项", Toast.LENGTH_SHORT);
            }
        });

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { //选择取消原因
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == rb1.getId()) {
                    mOrderCancelReason = rb1.getText().toString();
                } else if (checkedId == rb2.getId()) {
                    mOrderCancelReason = rb2.getText().toString();
                } else if (checkedId == rb3.getId()) {
                    mOrderCancelReason = rb3.getText().toString();
                } else if (checkedId == rb4.getId()) {
                    mOrderCancelReason = rb4.getText().toString();
                } else {
                    mOrderCancelReason = rb5.getText().toString();
                }
                mRsnReason = addReason.getText().toString().trim();
            }
        });
        dialog.setContentView(view);
        dialog.show();
    }


    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void toast(String msg) {

    }

    @Override
    public String getOrderNumber() {
        return mOrderNumber;
    }

    @Override
    public void refreshInfo() {
        mPresenter.loadOrderDetailData();
    }

    @Override
    public ApiOrderDetailInfo getOrderDetailInfo() {
        return mOrderDetailInfo;
    }

    @Override
    public String getOrderCancelReason() {
        return mOrderCancelReason;
    }

    @Override
    public void getOrderDetailDataSuc(ApiOrderDetailInfo data) {
        mOrderDetailInfo = data;
        refreshUI(data);
    }

    @Override
    public String getRsnRemark() {
        return mRsnReason;
    }


    private void refreshUI(ApiOrderDetailInfo datas) {
        //根据订单状态显示布局信息
        setOrderStatusLayoutInfo(datas);

        mTvOrderNumber.setText(datas.orderNo);
        mTvShopName.setText(datas.shopName);
        mTvReceiptAddress.setText(datas.consigneeAddress); //收货地址信息
        mTvReceiptNumber.setText(datas.consigneePhone);//收货人电话号
        mTvReceiptName.setText(datas.consignee); //收货人姓名
        mTvPayMethod.setText(datas.payWayText); //支付方式
        mTvRemarkInfo.setText(datas.remark); //备注信息
        mTvInvoice.setText(datas.invoiceTop); //发票抬头
        tvShipment.setText(String.format(getString(R.string.rmb_symbol), datas.deliveryPrice)); //配送费
        tvTotalMoney.setText(String.format(getString(R.string.rmb_symbol), datas.totalAmount)); //总金额

        //动态添加商品明细
        dynamicAddGoodsDetail(datas.goodsList);
    }


    private void setOrderStatusLayoutInfo(final ApiOrderDetailInfo datas) {

        if (datas.status == 0 || datas.status == 5) { //待接单
            mLLOrderSubmit.setVisibility(View.VISIBLE);
            mTvOrderTime.setText(datas.logList.get(0).creatTime);
            mTvOrderState.setText(datas.logList.get(0).detail);

            mTvTipInfo.setText(datas.status == 0 ? //根据状态显示不同 提示信息文字
                    getString(R.string.order_pending) : getString(R.string.order_pay_tips));
            mBtnPay.setVisibility(datas.status == 0 ? View.GONE : //支付按钮
                    View.VISIBLE);
            return;
        }


        //设置按钮文字.
        if (datas.status == 1) { //备货中
            mBtnState.setEnabled(false);
            mTitileRightText.setText("");
            mBtnState.setTextColor(getResources().getColor(R.color.gray));
            mBtnState.setText(getString(R.string.stock));
            mBtnState.setBackgroundResource(0);
        } else if (datas.status == 2) { //商家已发货
            mBtnState.setEnabled(true);
            mTitileRightText.setText(getString(R.string.complaints));
            mBtnState.setText(getString(R.string.receipt));
            mBtnState.setBackgroundColor(ContextCompat.getColor(this, R.color.color_fa515a));
        } else if (datas.status == 3) { //已签收
            mBtnState.setEnabled(true);
            mTitileRightText.setText(getString(R.string.complaints));
            mBtnState.setText(getString(R.string.evaluate));
            mBtnState.setBackgroundColor(ContextCompat.getColor(this, R.color.color_fa515a));
        } else if (datas.status == 4) {  //已取消
            mLLOrderSubmit.setVisibility(View.GONE);
            mBtnState.setEnabled(false);
            mBtnState.setTextColor(getResources().getColor(R.color.gray));
            mTitileRightText.setText(getString(R.string.complaints));
            mBtnState.setBackgroundResource(0);
            mBtnState.setText(String.format(getString(R.string.refund_detail_two),
                    datas.payStatus.equals("2") ?
                            getString(R.string.refunding) : getString(R.string.refund_suc_two)));
        }else {
            mLLOrderSubmit.setVisibility(View.GONE);
            mBtnState.setEnabled(false);
            mBtnState.setTextColor(getResources().getColor(R.color.gray));
            mTitileRightText.setText(getString(R.string.complaints));
            mBtnState.setBackgroundResource(0);
            mBtnState.setText("");
        }

        mBtnState.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (datas.status){

                    case 2://已发货，签收动作:
                        showDialogTwoBtn(getString(R.string.confirm_receipt), getString(R.string.receipt), getString(R.string.cancel), new ICallBack.TwoCallBack() {
                            @Override
                            public void left(CommDialog dialog) {
                                //调用订单签收接口
                                mCommPresenter.orderSign();
                            }

                            @Override
                            public void right(CommDialog dialog) {
                            }
                        });
                        break;
                    case 3://已经签收，需要评价

                        Bundle bundle = new Bundle();
                        bundle.putString("orderNumber",datas.orderNo);
                        intentJump(OrdersCommentsActivity.class,bundle);
                        break;

                }

            }
        });


        dynamicAddOrderStatus(datas.logList);
    }

    /**
     * 动态添加商品信息
     */
    private void dynamicAddGoodsDetail(List<ApiOrderDetailInfo.GoodsListBean> goodsList) {
        if (mLLGoodsDetail.getChildCount() != 0)
            mLLGoodsDetail.removeAllViews();

        for (int i = 0; i < goodsList.size(); i++) {
            final View view = LayoutInflater.from(this).inflate(R.layout.item_order_detail, new FrameLayout(this), false);
            TextView goodsName = (TextView) view.findViewById(R.id.tv_goods_name);
            TextView goodsPrice = (TextView) view.findViewById(R.id.tv_goods_price);
            TextView goodsCount = (TextView) view.findViewById(R.id.tv_goods_count);

            goodsName.setText(goodsList.get(i).goodsName);
            goodsPrice.setText(String.format(getString(R.string.rmb_symbol), goodsList.get(i).goodsPrice));
            goodsCount.setText(String.format(getContext().getString(R.string.x1), goodsList.get(i).goodsNo));
            mLLGoodsDetail.addView(view);

            if (i == goodsList.size() - 1)
                view.findViewById(R.id.line1).setVisibility(View.GONE);
        }
    }

    /**
     * 动态添加日志状态
     */
    private void dynamicAddOrderStatus(List<ApiOrderDetailInfo.LogListBean> logList) {

        mRLReceiveOrder.setVisibility(View.VISIBLE);

        if (mLLDynamicCirclePoint.getChildCount() != 0)
            mLLDynamicCirclePoint.removeAllViews();

        if (mLLDynamicOrderStauts.getChildCount() != 0)
            mLLDynamicOrderStauts.removeAllViews();


        for (int i = 0; i < logList.size(); i++) {

            ApiOrderDetailInfo.LogListBean logListBean = logList.get(i);

            View pointView = LayoutInflater.from(this).inflate(R.layout.dynamic_order_detail_circle_point, new FrameLayout(this), false);
            View statusView = LayoutInflater.from(this).inflate(R.layout.dynamic_order_detail_status, new FrameLayout(this), false);

            ((TextView) statusView.findViewById(R.id.tv_order_time)).setText(logListBean.creatTime);
            ((TextView) statusView.findViewById(R.id.tv_order_detail)).setText(logListBean.detail);

            if (i == logList.size() - 1) {
                pointView.findViewById(R.id.line).setVisibility(View.GONE);
                ((ImageView) pointView.findViewById(R.id.iv_circle)).setImageResource(R.mipmap.order_point_blue);
            }

            mLLDynamicOrderStauts.addView(statusView);
            mLLDynamicCirclePoint.addView(pointView);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case IntentUtils.REQUEST_CODE_CALLPHONE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    IntentUtils.realCallPhone(mContext, mOrderDetailInfo.consigneePhone);
                break;
        }
    }
}
